<template>
  <el-upload
    class="avatar-uploader"
    :action="apiPath"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="value" :src="value" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<script>
export default {
  props: {
    apiPath: {
      default: "",
      type: String,
    },
    value: {
      default: "",
      type: String,
    },
  },
  //   data() {
  //     return {
  //       imageUrl: "",
  //     };
  //   },
  methods: {
    handleAvatarSuccess(res) {
      //   this.imageUrl = URL.createObjectURL(file.raw);
      if (res.imageUrl) {
        this.$emit("input", res.imageUrl);
      }
    },
    beforeAvatarUpload(file) {
      const isValidFormat =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isValidFormat) {
        this.$message.error("图片必须为jpg或者png格式");
      }
      if (!isLt10M) {
        this.$message.error("图片大小不能超过10M");
      }
      return isValidFormat && isLt10M;
    },
  },
};
</script>
